如何使用点表示法在 javascript 中的数组和对象上创建日志方法?
function log(...k){
console.log.apply(console, k)
}
log('hello') //=> prints hello
//I want to do this for arrays and objects using the dot notation
['hello','world'].log() //=> prints ['hello', 'world']
{'hello':'world'}.log() //=> prints {'hello', 'world'}Run Code Online (Sandbox Code Playgroud)
我试图使用每个数组在两个数组中找到公共数字.正如预期的那样,当我在if语句中检查相等性时,每个都不起作用.但是,它在我的第二个例子中确实有效.不幸的是,我不明白为什么.有人可以解释为什么第二个例子在第一个例子没有的地方有效吗
// Will not work here
function findCommonNumbersInArrays(arOne, arTwo) {
var cm = [];
for (var i = 0; i <= arOne.length; i++) {
if (arTwo.every(a => a === arOne[i])) {
cm.push(arOne[i]);
}
}
return cm;
}
console.log('These are the common numbers: ' + findCommonNumbersInArrays([1, 2, 3, 4, 5], [3, 4, 6, 7, 8]));
// Works here
function common(arOne, arTwo) {
var cm = [];
for (var i = 0; i <= arOne.length; i++) {
if (!arTwo.every(a => a !== …Run Code Online (Sandbox Code Playgroud)