2016-12-30 33 views
-2

我運行這個功能扁平化的數組:我的Flatten數組方法在控制檯中工作,但不是codewars?

function flatten(array) { 
 
    return array.join(',').split(','); 
 
} 
 

 
array = [[1,2,3],[1,2,3]]; 
 
alert(flatten(array));

它的工作在下面的代碼片段,但是當我嘗試在該網站codewars使用它,我得到「\」插入在每個角色,導致測試失敗。這是爲什麼?

這是輸出:

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

你問的[適當的方法來壓扁多維數組](http://stackoverflow.com/q/27266550/5743988)?或者你只是在詢問有關正在插入的斜槓? – 4castle

+0

只是正在插入的斜槓。我已經實施了正確的解決方案。 @ 4castle –

+1

你可能想編輯你的問題,以便它顯示什麼codewars顯示。 – 4castle

回答

0

您可以使用Array.prototype.concat()

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字符串轉義序列。

+0

OP實際上並沒有對任何替代方案感興趣。 – 4castle

相關問題