【问题标题】:get element from arbitrary list in javascript从javascript中的任意列表中获取元素
【发布时间】:2014-12-13 17:15:56
【问题描述】:

我在 javascript 中有一个函数,我需要在其中检索列表的最后一个元素。列表可以是数组、字符串、数字列表(不是数组)。我尝试将列表转换为字符串,然后转换为数组并按索引检索它,但这不起作用。

这是我试过的代码:

  function last(list){
      var array = new String(list);
      array = array.split("");
      return array[array.length-1];
  }

我不明白问题出在哪里,因为测试套件显示的是 Expected: 5 而不是 got: 5 我正在使用代码大战并且没有编写测试。它期待一个数字并得到一个字符串'5'吗?我还不太了解松散类型语言中的类型。

【问题讨论】:

  • list in numbers (not array) - 那会是什么?
  • 你能发布测试吗?
  • @thefourtheye 这是测试之一 Test.assertEquals(last(1,"b",3,"d",5), 5);//-- arguments
  • @NicolásStraubValdivieso 以下是我可见的测试,它在测试失败后停止运行,因此它在第一个停止。 Test.assertEquals(last([1,2,3,4,5]), 5); //-- 数组 Test.assertEquals(last("abcde"), "e"); //-- 字符串 Test.assertEquals(last(1,"b",3,"d",5), 5);//-- 参数
  • Is it expecting a Number and getting a String '5' ? 很有可能!

标签: javascript arrays type-conversion


【解决方案1】:

来自 cmets,我认为您的意思是要返回数组中的最后一个元素、字符串中的最后一个字符,或者如果传递了多个参数,则返回最后一个参数。这样就可以了:

function last() {
    if (arguments.length > 1) { // first we handle the case of multiple arguments
        return Array.prototype.pop.call(arguments);
    }
    value = arguments[0]
    if (typeof value === 'string') { // next, let's handle strings
        return value.split('').pop();
    }

    if (Object.prototype.toString.call( [] ) === '[object Array]') {// Arrays are of type object in js, so we need to do a weird check
        return value.pop();
    }
}

arguments 是一个伪数组,其中包含传递给函数的所有参数,因此对于last(1,2,3,4,5)arguments 大致为[1,2,3,4,5]。不完全是这样,因为arguments 有所有的 args 和一个长度属性,但它的原型不是Array,所以它不是真正的[1,2,3,4,5] 并且缺少数组的所有功能。这就是为什么我们需要在 arguments 的上下文中调用 pop (在 javascript 中,Function.prototype.call 调用将第一个参数作为 this 的值传递的函数,并将所有其余参数放入 arguments 伪-array,例如last.call([], 1, 2, 3) 将在新数组的上下文中调用last,而arguments 大致等于[1,2,3]

其余代码非常简单,除了检查value 是否为数组,here 将进一步解释。

最后,pop 是一个数组方法,它从数组中移除最后一个元素并返回它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 2015-03-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    相关资源
    最近更新 更多