题目描述
输入
'12'
输出
12
输入
复制'12px'
输出
复制12
输入
'0x12'
输出
0
function parse2Int(num) {
var type = typeof num;
if (type === "number") {
if (num % 1 === 0) {
return num;
} else {
return num-num%1;
}
} else if (type === "string") {
var s = "", n0 = "0".charCodeAt(0), n9 = "9".charCodeAt(0);
for (var i = 0; i < num.length; i++) {
var c = num.charCodeAt(i);
if (n0 <= c && c <= n9) {
s += num.charAt(i);
} else {
break;
}
}
function s2i(s) {
var n = 0, n0 = "0".charCodeAt(0);
for (var i = 0; i < s.length; i++) {
n = 10*n + (s.charCodeAt(i)-n0);
}
return n;
}
return s2i(s);
}
return NaN;
}
* 流程控制
实现 fizzBuzz 函数,参数 num 与返回值的关系如下:
1、如果 num 能同时被 3 和 5 整除,返回字符串 fizzbuzz
2、如果 num 能被 3 整除,返回字符串 fizz
3、如果 num 能被 5 整除,返回字符串 buzz
4、如果参数为空或者不是 Number 类型,返回 false
5、其余情况,返回参数 num
Input:15 Output: fizzbuzz
function fizzBuzz(num) {
if (!num) {return !1;}
if (typeof num === "number") {
var a = num%3===0, b = num%5==0;
return a&&b ? "fizzbuzz" : a ? "fizz" : b ? "buzz" : num;
}
return !1;
}
* 求 a 和 b 相乘的值,a 和 b 可能是小数,需要注意结果的精度问题
input: 3, 0.0001
output: 0.0003
function multiply(a, b) {
var d1 = d2 = 0;
while (a%1 !== 0) {
a *= 10;
d1++;
}
while (b%1 !== 0) {
b *= 10;
d2++;
}
var d = d1+d2;
return parseFloat(a * b * Math.pow(0.1, d)).toFixed(d);
}
javascript对象克隆:
Object.prototype.clone = function() {
// Handle null or undefined or function
if (null == this || "object" != typeof this)
return this;
// Handle the 3 simple types, Number and String and Boolean
if(this instanceof Number || this instanceof String || this instanceof Boolean)
return this.valueOf();
// Handle Date
if (this instanceof Date) {
var copy = new Date();
copy.setTime(this.getTime());
return copy;
}
// Handle Array or Object
if (this instanceof Object || this instanceof Array) {
var copy = (this instanceof Array)?[]:{};
for (var attr in this) {
if (this.hasOwnProperty(attr))
copy[attr] = this[attr]?this[attr].clone():this[attr];
}
return copy;
}
throw new Error("Unable to clone obj! Its type isn't supported.");
}
但是这样写会与jQuery冲突
为了不污染原型链
function clone(o) {
// Handle null or undefined or function
if (null == o || "object" != typeof o)
return o;
// Handle the 3 simple types, Number and String and Boolean
if(o instanceof Number || o instanceof String || o instanceof Boolean)
return o.valueOf();
// Handle Date
if (o instanceof Date) {
var copy = new Date();
copy.setTime(o.getTime());
return copy;
}
// Handle Array or Object
if (o instanceof Object || o instanceof Array) {
var copy = (o instanceof Array)?[]:{};
for (var attr in o) {
if (o.hasOwnProperty(attr))
copy[attr] = o[attr]? clone(o[attr]):o[attr];
}
return copy;
}
throw new Error("Unable to clone obj! Its type isn't supported.");
}