正文
我也是这样/(ㄒoㄒ)/~~
这里主要是考虑了优先级。
+ 的优先级是高于 ? 的
,
所以执行顺序是
val === 'stmg' => true'Value is' + true => 'Value is true''Value is true ' ? 'Something' : 'Nothing' => 'Something'
所以结果为
'Something'
第5题:
var name = 'World!';
(function () { if (typeof name === 'undefined') { var name = 'Jack'; console.log('Goodbye ' + name);
} else { console.log('Hello ' + name);
}
})();
解析:主要考虑变量声明提升,本题相当于把name声明到顶部但是未定义。
这里扩充一下函数提升
dohois(); donothois(); function dohois () { console.log("提升了");
}var donothois = function () { console.log("没有提升");
}
所以结果为
Goodbye Jack
第6道:
var END = Math.pow(2, 53);var START = END - 100;var count = 0;for (var i = START; i <= END; i++) console.log(count);
解析:JS里Math.pow(2, 53)是可以表示的最大值,最大值加1还是最大值。发生的情况是这样的 :
Math.pow(2, 53) == Math.pow(2, 53) + 1
,所以永远不可能大于Math.pow(2, 53)。
console.log(Infinity); console.log(Infinity + 1);
所以结果是
无限循环
第7道:
var ary = [0,1,2];
ary[10] = 10;
ary.filter(function(x) { return x === undefined;});
解析:首先需要理解稀疏数组和密集数组
创建一个稀疏数组,遍历稀疏数组时,会发现这个数组并没有元素,js会跳过这些坑。
var a = new Array(3);
console.log(a); var arr = [];
arr[0] = 1;
arr[100] = 100;
a.map(function (x, i) {return i});
创建一个密集数组,可以遍历到这些数组元素
var a = Array.apply(null, Array(3));console.log(a); a.map(function (x, i) {return i});