JavaScript 把数组里的0放到后面

You are NOT allowed to use any temporary arrays or objects. You are also not allowed to use any Array.prototype or Object.prototype methods.

console.log(removeZeros([7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]));
//[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
  • my answer
function removeZeros(arr) {
    var len = arr.length;
    var temp;
    for (var i = 0; i < len; i++) {
        if (arr[i] === 0 || arr[i] === '0') {
            temp = arr[i];
            for (var j = i--; j < arr.length-1; j++) {
                arr[j] = arr[j+1];
            }
            arr[arr.length-1] = temp;
            len--;
        }
    }
    return arr;
}
posted @ 2017-09-12 20:08  芒果夏夏  阅读(365)  评论(0编辑  收藏  举报