我正在尝试在Google Apps脚本中向2D数组添加值。以下代码运行,但不是数组所需的输出。
function fruitList() {
var fruitArray = [['apple'], ['banana'], ['cherry']];
var newArray = [];
fruitArray.forEach(function(value) {
newArray.push([value, "name"]);
});
}
我的代码产生以下输出:
[ [ [ 'apple' ], 'name' ], [ [ 'banana' ], 'name' ], [ [ 'cherry' ], 'name' ] ]
我想要的输出是:
[ [ 'apple', 'name' ], [ 'banana', 'name' ], [ 'cherry', 'name' ] ]
value
是一个数组。不是字符串/基元值。您可以使用析构函数赋值来获得实际值:
fruitArray.forEach(function([/*destructure 1D array*/value]) {
newArray.push([value, "name"]);
});
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
function fruitList() {
var fruitArray = [['apple'], ['banana'], ['cherry']];
var newArray = [];
fruitArray.forEach(function([value]) {
newArray.push([value, "name"]);
});
console.info(newArray)
}
fruitList()
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
添加一个值:
function fruitList() {
var fruitArray = [['apple'], ['banana'], ['cherry']];
var newArray = [];
fruitArray.forEach(function(value) {
newArray.push([value[0], "name"]);
});
Logger.log(JSON.stringify(newArray))
}
Execution log
3:27:33 PM Notice Execution started
3:27:34 PM Info [["apple","name"],["banana","name"],["cherry","name"]]
3:27:34 PM Notice Execution completed