晚上好,我想创建一个由多个值的数组中所做的字符串。 这里有一个例子:
textArray = []
var wordOne = "Hello";
var wordTwo = "World";
if (wordOne != "foo"){
textArray.push(wordOne);
}
console.println(textArray[0] + ", " + textArray[1]);
\\It would print out "Hello, undefined"\\
\\ I use 'console.println' since I'm working on Adobe software\\
基本上,有时存在的值不添加到我的数组的时刻,但我还是希望能够把它打印出来没有“不确定”来了。有没有什么办法解决这一问题?
只要使用加入
textArray = []
var wordOne = "Hello";
var wordTwo = "World";
if (wordOne != "foo"){
textArray.push(wordOne);
}
console.log(textArray.join(', '));
只是遍历你的阵列的知名迭代的方法之一。然后,你将无法超越的数组的长度。如果您有差距的数组中,因为你不分配一个值,一些阵列插槽,那么你可以跳过与forEach
这些差距:
var arr = [];
// We leave a gap at [0]
arr[1] = "Test";
// Another gap at [2]
arr[3] = "Trial";
arr.forEach((x, i) => console.log(i, x));
你只推一个元素数组中,然后访问两个元素,这就是为什么你undefined
第二数组访问。
你可以只添加一个空字符串,如果没有元素:
var textArray = []
var wordOne = "Hello";
var wordTwo = "World";
if (wordOne != "foo"){
textArray.push(wordOne);
}
else {
textArray.push('')
}
console.println(textArray[0] + ", " + textArray[1]);
//will print: 'Hello,'
你应该推动这两个变量,这就是为什么你得到一个未定义的索引1起因您的数组只有一个元素conatain:
var textArray = [];
const wordOne = "Hello";
const wordTwo = "World";
textArray = [(wordOne !== "foo" && wordOne), (wordTwo !== "foo" && wordTwo)];
console.log(textArray.join(", "));