如何在 javascript 上使用 push 方法创建新数组
how to create new array using push method on javascript
我正在尝试使用推送方法创建类似于 myCourses
数组的新数组。
但在某种程度上,它一次只记录一个字符串,而不是像 myCourses
array:
这样创建一个新的类似数组
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)
}
根据我上面的评论,正确的解决方案(如果我们接受以这种方式创建新数组,使用 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"]
我正在尝试使用推送方法创建类似于 myCourses
数组的新数组。
但在某种程度上,它一次只记录一个字符串,而不是像 myCourses
array:
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)
}
根据我上面的评论,正确的解决方案(如果我们接受以这种方式创建新数组,使用 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"]