【问题标题】:how to create new array using push method on javascript如何在 javascript 上使用 push 方法创建新数组
【发布时间】:2022-01-18 13:29:47
【问题描述】:

我正在尝试使用 push 方法创建类似于 myCourses 数组的新数组。

但在某种程度上,它一次只记录一个字符串,而不是创建一个新的类似数组,如 myCourses 数组:

let myCourses = ["Learn CSS Animations", "UI Design Fundamentals", "Intro to Clean Code"]
for (let i = 0; i < myCourses.length; i++) {
    let a = []
    a.push( a += myCourses[i] )
    console.log(a) 
}

【问题讨论】:

  • let a = []放在循环之前(现在你在每个循环中重新声明a)和a.push( myCourses[i] )里面。
  • 使用此代码a += myCourses[i],你认为你得到了什么?
  • 您可以将整个代码替换为const a = Array.from(myCourses)const a = [...myCourses]const a = myCourses.slice()。甚至const a = myCourses.map(x =&gt; x).

标签: javascript arrays push


【解决方案1】:

由于我上面的评论,正确的解决方案(如果我们接受以这种方式创建新数组,使用 for 循环)是

let myCourses = ["Learn CSS Animations", "UI Design Fundamentals", "Intro to Clean Code"]

// declare a only once
let a = []
for (let i = 0; i < myCourses.length; i++) {
    // a += myCourses[i] is non-sense in this case
    a.push( myCourses[i] )
}

console.log(a);
// write into console the result, just once, not in every loop 
// returns ["Learn CSS Animations", "UI Design Fundamentals", "Intro to Clean Code"]

【讨论】:

  • 切入正题,谢谢。 a += myCourses[i] 在这种情况下是没有意义的,因为 push 方法已经这样做了
  • @tsurihe 很高兴为您提供帮助。 a+=myCourses[i] 是有效的构造,应该在其他情况下使用,而不是在这里。祝你在下一个编程任务中好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多