Javascript | Set all values of an array

前端 未结 8 761
清酒与你
清酒与你 2020-12-29 19:45

Code

var cool = new Array(3);
cool[setAll] = 42; //cool[setAll] is just a pseudo selector..
alert(cool);

Result

相关标签:
8条回答
  • 2020-12-29 19:47

    Use a for loop and set each one in turn.

    0 讨论(0)
  • 2020-12-29 19:50

    The ES6 approach is very clean. So first you initialize an array of x length, and then call the fill method on it.

    let arr = new Array(3).fill(9)
    

    this will create an array with 3 elements like:

    [9, 9, 9]
    
    0 讨论(0)
  • 2020-12-29 19:50

    map is the most logical solution for this problem.

    let xs = [1, 2, 3];
    xs = xs.map(x => 42);
    xs // -> [42, 42, 42]
    

    However, if there is a chance that the array is sparse, you'll need to use for or, even better, for .. of.

    See:

    • https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
    0 讨论(0)
  • 2020-12-29 20:01

    Found this while working with Epicycles - clearly works - where 'p' is invisible to my eyes.

    /** Convert a set of picture points to a set of Cartesian coordinates */
    function toCartesian(points, scale) {
      const x_max = Math.max(...points.map(p=>p[0])),
      y_max = Math.max(...points.map(p=>p[1])),
      x_min = Math.min(...points.map(p=>p[0])),
      y_min = Math.min(...points.map(p=>p[1])),
      signed_x_max = Math.floor((x_max - x_min + 1) / 2),
      signed_y_max = Math.floor((y_max - y_min + 1) / 2);
    
      return points.map(p=>
      [ -scale * (signed_x_max - p[0] + x_min),
      scale * (signed_y_max - p[1] + y_min) ] );
    }
    
    0 讨论(0)
  • 2020-12-29 20:04

    There's no built-in way, you'll have to loop over all of them:

    function setAll(a, v) {
        var i, n = a.length;
        for (i = 0; i < n; ++i) {
            a[i] = v;
        }
    }
    

    http://jsfiddle.net/alnitak/xG88A/

    If you really want, do this:

    Array.prototype.setAll = function(v) {
        var i, n = this.length;
        for (i = 0; i < n; ++i) {
            this[i] = v;
        }
    };
    

    and then you could actually do cool.setAll(42) (see http://jsfiddle.net/alnitak/ee3hb/).

    Some people frown upon extending the prototype of built-in types, though.

    EDIT ES5 introduced a way to safely extend both Object.prototype and Array.prototype without breaking for ... in ... enumeration:

    Object.defineProperty(Array.prototype, 'setAll', {
        value: function(v) {
            ...
        }
    });
    

    EDIT 2 In ES6 draft there's also now Array.prototype.fill, usage cool.fill(42)

    0 讨论(0)
  • 2020-12-29 20:05

    It's 2019 and you should be using this:

    let arr = [...Array(20)].fill(10)

    So basically 20 is the length or a new instantiated Array.

    0 讨论(0)
提交回复
热议问题