【问题标题】:JavaScript: Test if input args are arrays; If yes, then merge arrays into one big array [duplicate]JavaScript:测试输入参数是否为数组;如果是,则将数组合并为一个大数组[重复]
【发布时间】:2019-11-12 13:03:09
【问题描述】:

我有以下变量是数组:

const gumBrands = ['orbit', 'trident', 'chiclet', 'strident'];

const mintBrands = ['altoids', 'certs', 'breath savers', 'tic tac'];

下面我有以下使用变量作为输入参数的函数:

function shallowCopy (arrOne, arrTwo) {

    if (arrOne.constructor === 'Array'){

        return [...arrOne, ...arrTwo]; 
    }

    else {
        console.log('test this'); 
    }
}


shallowCopy(gumBrands, mintBrands)

我期待我的代码返回:

[ 'orbit',
  'trident',
  'chiclet',
  'strident',
  'altoids',
  'certs',
  'breath savers',
  'tic tac' ]

代码运行我的 else 语句并返回:test this

我做错了什么?

【问题讨论】:

    标签: javascript arrays function if-statement arguments


    【解决方案1】:

    .constructor 不包含字符串"Array",而是对全局Array 对象的引用。

    请注意,数组可以被子类化,它们的.constructor 是不同的。您可能需要考虑与instanceof Array 联系。

    【讨论】:

      猜你喜欢
      • 2011-02-15
      • 2017-03-22
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 2017-03-20
      • 2012-05-10
      • 2014-06-29
      • 2012-08-20
      相关资源
      最近更新 更多