【问题标题】:Js: last value set and getJs:最后一个值设置和获取
【发布时间】:2020-11-01 04:54:27
【问题描述】:

从数组中选择最后一个元素的最快方法是array[length - 1]

但是,当我得到一个更大的嵌套数组时,我会得到这样的结果:

let last_item = pathsry[
    pathsry.length - 1
    ][
        pathsry[
            pathsry.length - 1
        ].length - 1
    ]

这不是好人,因此我重写了以下以获取最后一个值。

// get item at last index
Array.prototype.last = String.prototype.last = function(){
  return this[this.length - 1];
}

这让我得到

var arr = [[1, 2], [2, 3], [['a', 'b'], ['c', 'd']]];
console.log(arr.last().last().last());
// 'd'

但是,如果我尝试设置:

Array.prototype.last = function(){
    return this[this.length - 1];
}

var arr = [[1, 2], [2, 3], [['a', 'b'], ['c', 'd']]];
arr.last().last().last() = 'dd';

// ReferenceError: Invalid left-hand side in assignment

有没有一种方法可以编写一个函数,该函数将一个数字作为参数,表示嵌套切片,以及一个可选参数的设置值,其中:

function arrayLast(arr, nes, val){
    // ...
}

var arra = [[1, 2], [2, 3], [['a', 'b'], ['c', 'd']]];

console.log(arrayLast(arra, 3));
// d

arrayLast(arra, 3, 'dd');
console.log(arra);
// arr = [[1, 2], [2, 3], [['a', 'b'], ['c', 'dd']]]

感谢您的帮助

【问题讨论】:

  • 我特别不想使用flat,因为它会降低性能

标签: javascript arrays get set


【解决方案1】:

这应该有帮助!

Array.prototype.last = function(val=null) {
  if (this.length === 0) {
    if (val) this[0] = val;
    else return null; 
  }
  
  temp = this;
  while(typeof temp[temp.length-1] === "object") {
    temp = temp[temp.length-1];
  }
  
  if (val) temp[temp.length-1] = val; //Setter  
  else return temp[temp.length-1]; //Getter
  
}

var arr = [[1, 2], [2, 3], [['a', 'b'], ['c', 'd']]];
console.log(arr.last()); // 'd'
    
arr.last("dd"); 
console.log(arr); // [ [ 1, 2 ], [ 2, 3 ], [ [ 'a', 'b' ], [ 'c', 'dd' ] ] ]

【讨论】:

    猜你喜欢
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多