[JS practice] For the sake of argument(判断全数数组)

Title:
For the sake of argument(判断一个数组中是否全部为数字)

Description:
Write a function named numbers that returns true if all the parameters it is passed are numbers. Otherwise, the function should return false. The function should accept any number of parameters.

实现一个方法接受一个数组作为参数,当数组中只包含数字时则返回true,否则返回false。
考察对javascript基本数据类型的判断。

Example usage:
numbers(1, 4, 3, 2, 5); // true
numbers(1, “a”, 3); // false

Normal solution:

function numbers() {
	for (var prop in arguments) {
  	if(typeof arguments[prop] != "number") {
    	return false;
    }
  }
  return true;
}

Best solution:

function numbers() {
  return Array.prototype.reduce.call(arguments, function(previousValue, currentValue) {
    return !(typeof currentValue == "number") ? previousValue + 1 : previousValue;
  }, 0) === 0;
}

Ref. from codewars

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s