检查数组是否? [英] Check if array or not?

查看:75
本文介绍了检查数组是否?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 function sumAll(a) {
    'use strict';
    var result = 0;
    for (var i = 0; i < a.length; ++i) {
        result = result +  a[i];
    }
    return result;
}





我的任务是修改这段代码,这样当传递的第一个参数不是数组时,函数返回那个论点。我是JS的新手,我不知道如何处理这个问题。



sumAll(18)应该返回18

sumAll('Hello')应该返回'Hello'



My assignment is to modify this code so that when the first argument passed is NOT an array, the function returns that argument. I'm quite new to JS and I'm not on how to approach this.

sumAll(18) should return 18
sumAll('Hello') should return 'Hello'

推荐答案

function sumAll(a) 
{
  if (Array.isArray(a)) {
        alert('Yes')
  }
  else {
    alert('No')
  }
}



现在,你有代码确定它是否是一个数组。继续这样做。请记住,作业是为了学习目的。如果我们提供完整的解决方案,您将无法从中学到任何东西。



经常使用Google。您将学习并获得解决方案。



问候..


Now, you have code to determine whether its an array or not. proceed with that. Remember, assignments are meant for learning purpose. If we provide complete solution than you won't learn anything out of it.

Use Google often.You will learn as well as get the solution.

Regards..


function sumAll(a) {
    'use strict';
    var result = 0;

    if(!a){
        return a;
    }

    if(!a instanceof Array){
        return a;
    }

    for (var i = 0; i < a.length; ++i) {
        result = result +  a[i];
    }
    return result;
}


这篇关于检查数组是否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆