天然迭代器
有一个数n=5,不用for循环,怎么返回[1,2,3,4,5]这样一个数组
function iter(n) {
return Array(n + 1).toString().
replace(/,/g, function(a, b) {return b}).
split("");
}
说明
我认为最重要的是,replace函数的第二个参数,可以是函数,提供了一个动态的可能性,需要了解返回函数的参数的定义
写道
不使用中间变量,交换int型的 a, b两个变量的值。
//by ppchen
var a = 10, b = 2;
a = a + b;
b = a - b;
a = a - b;
//by Mr.司马
var a = 10000,b=245
a = a^b;
b = b^a;
a = a ^b;
//by cloudgamer
var a = 33,b=44
a=[a,b]
b=a[0]
a=a[1]
//by Mr.司马
var a = 23,b=454;
a = {a:b,b:a};
b = a.b;
a = a.a;
写道
1、2种解法是普遍解,只能交换数字,而3、4种则适用性更广
写道
如何不使用Math.random实现随机数
// The idea of random mehtod is taken from
// http://ianbullard.squarespace.com/journal/2009/4/28/why-you-should-never-use-rand.html
var random = (function(){
var high = 1, low = 1 ^ 0x49616E42;
var shuffle = function(seed){
high = seed;
low = seed ^ 0x49616E42;
}
return function(){
var a = new Date()-0
shuffle(a);
high = (high << 16) + (high >> 16);
high += low;
low += high;
return high;
}
})();
p(random())