【问题标题】:Array returning NaN for String values in JS数组返回 JS 中字符串值的 NaN
【发布时间】:2019-07-17 18:23:56
【问题描述】:

我正在编写一个程序,通过使用花色和牌值来制作一副牌。我正在为西装循环内的卡片运行一个 for 循环和另一个嵌套的 for 循环,并尝试在一个名为“deck”的空数组中打印所有组合(52)。在添加值后尝试记录甲板数组时,我在甲板数组中有字符串的值中得到“NaN”。

我知道 NaN 的意思是“不是数字”,这就是为什么我在数组中打印字符串值时收到此错误的原因。

如何打印字符串值?

代码:

let suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
let cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

let deck = [];

for (let i = 0; i < suits.length; i++) {
  for (let j = 0; j < cards.length; j++) {
    deck.push(+cards[j] + "of" + suits[i]);
  }
}
console.log(deck[1]);
for (let k = 0; k < deck.length; k++) {
  console.log(deck[k]);
}

【问题讨论】:

  • 如果您知道为什么会收到NaN,那么问题是什么?
  • 如何打印字符串值?
  • 这个+"Ace"无法强制执行
  • 停止使用+cards[j] 强制他们使用数字?
  • 为什么不只是: deck.push(cards[j] + "of" + suits[i]);你不需要强制。

标签: javascript arrays nan


【解决方案1】:
deck.push(+cards[j] + "of" + suits[i]);

deck.push(cards[j] + "of" + suits[i]);


这个unary operator+variable 将尝试将值转换为一个数字,类似于parseInt()Number()。您不能将字符串 "Ace" 转换为数字,因此它会返回 "NaN" 并将其连接到字符串的开头。

您实际上不需要此一元运算符,因为通过将数字与字符串 (+ "of" +) 连接,您已经将整数强制转换为字符串,这是您在这种情况下尝试实现的数据类型。

JS 中的强制: JavaScript type coercion explained


并且用 ES6..

写得更简洁
var deck = [].concat(
    ...suits.map(suit =>
       cards.map(card => card +' of '+ suit)
    )
)

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 1970-01-01
    • 2013-12-12
    • 2018-05-11
    • 2021-08-06
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    相关资源
    最近更新 更多