【发布时间】: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 => x).
标签: javascript arrays push