如果满足条件,则映射数组中的字母 REACT

时间:2021-05-06 15:32:54

标签: html reactjs dictionary if-statement

我有一个这样的状态:

const [word, setWord] = useState([
    {
      letters: ["r", "e", "a", "c", "t"],
      shows: [0, 0, 0, 0, 1],
    },
  ]);

如果shows[i] == 1,我想呈现一个字母,否则我想呈现"_"

我如何在 React 中使用地图(或其他方式)来做到这一点?我的意思是这样的:

map((letter, show) => (
    show == 1 ? letter : '_'
))

3 个答案:

答案 0 :(得分:1)

您可以使用.map()

const word = {
  letters: ["r", "e", "a", "c", "t"],
  shows: [0, 0, 0, 0, 1],
}

console.log(word.letters.map((l, i) => word.shows[i] === 0 ? "_" : l))

word 在问题中是一个数组。除非确实需要,否则我建议您将其设为对象。

答案 1 :(得分:1)

你也可以尝试对象解构

const { letters, shows } = word[0]
console.log(letters.map((l, i) => (shows[i] == 1 ? l : '_')))

答案 2 :(得分:1)

    let words = [
        {
          letters: ["r", "e", "a", "c", "t"],
          shows: [0, 0, 0, 0, 1],
        },
        {
          letters: ["j", "a", "v", "a", "s", "c", "r", "i", "p", "t"],
          shows: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        },
      ]

    /* you can map the words */
                
   words.map(word => 
              console.log(word.letters.map((letter, index) =>
                (word.shows[index] == 1 ? letter : "_")))