zoukankan      html  css  js  c++  java
  • JavaScript----- Moving Zeros To The End

    Description:

    Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.

    console.log(moveZeros([false,10,0,1,2,0,1,3,"a"])); 
    // returns[false,1,1,2,1,3,"a",0,0]
    

    my answer:

    function moveZeros(arr) {
      var j = 0;
      for (var i = 0; i < arr.length; i++) {
        if(arr[i] === 0) {
          arr.splice(i,1);   //找出0所在位置并用splice()方法删除0
          j += 1;
          i = i - 1;     //计算被删除的0的总个数
        }
      }
      for (var k = 0; k < j; k++){  //为数组添加被删除的0;
        arr.push(0);
      }
      return arr;
    }
    

    best answer,使用filter()方法

    • filter() 方法: 创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
    • filter() 不会改变原始数组。
    function moveZeros(arr) {
      return arr.filter(function(x) {return x !== 0}).concat(arr.filter(function(x) {return x === 0;}));
    }
    
  • 相关阅读:
    怎么在myeclipse中怎么集成Tomcat。
    JSP .基础概念
    继承
    封装
    什么是面向对象
    数据排序
    开发的套路
    Javabean规范
    转发和重定向
    md5加密
  • 原文地址:https://www.cnblogs.com/kid2333/p/7506070.html
Copyright © 2011-2022 走看看