我正在运行此功能来展平数组:
function flatten(array) {
return array.join(',').split(',');
}
array = [[1,2,3],[1,2,3]];
alert(flatten(array));
它正在下面的片段中工作,但是当我尝试在站点代码中使用它时,我会在每个字符处插入'\',导致测试失败。那是为什么?
这是输出:
Time: 496ms Passed: 0 Failed: 78
Test Results:
Basic tests
✘ Expected: '[]', instead got: '[\'\']'
✘ Expected: '[]', instead got: '[\'\', \'\']'
✘ Expected: '[1]', instead got: '[\'\', \'1\']'
✘ Expected: '[1, 2]', instead got: '[\'\', \'\', \'\', \'2\', \'\', \'1\']'
✘ Expected: '[1, 2, 3, 4, 5, 6, 7, 8, 9]', instead got: '[\'3\', \'2\', \'1\', \'7\', \'9\', \'8\', \'6\', \'4\', \'5\']'
✘ Expected: '[1, 2, 3, 4, 5, 6, 100]', instead got: '[\'1\', \'3\', \'5\', \'100\', \'2\', \'4\', \'6\']'
✘ Expected: '[111, 222, 333, 444, 555, 666, 777, 888, 999]', instead got: '[\'111\', \'999\', \'222\', \'333\', \'444\', \'888\', \'777\', \'666\', \'555\']'
Completed in 7ms
这些是测试:
describe("Example test cases", function() {
Test.assertSimilar(flattenAndSort([]), []);
Test.assertSimilar(flattenAndSort([[], [1]]), [1]);
Test.assertSimilar(flattenAndSort([[3, 2, 1], [7, 9, 8], [6, 4, 5]]), [1, 2, 3, 4, 5, 6, 7, 8, 9]);
Test.assertSimilar(flattenAndSort([[1, 3, 5], [100], [2, 4, 6]]), [1, 2, 3, 4, 5, 6, 100]);
});
答案 0 :(得分:0)
var array = [[1,2,3], [1,2,3]];
var result = array[0].concat(array[1]);
console.log(result);

您将数字转换为字符串的功能,因此结果是一个字符串数组:
function flatten(array) {
return array.join(',').split(',');
}
var array = [[1,2,3],[1,2,3]];
console.log(flatten(array));

插入反斜杠以转义单引号 - 由于某种原因,文本显示为带有转义序列的JavaScript字符串。