数组,字符串,数学函数

2016-08-24  本文已影响16人  _Josh

问答

  • 数组方法里push、pop、shift、unshift、join、split分别是什么作用。

代码

用 splice 实现 push、pop、shift、unshift方法
var prod = { name: '女装', styles: ['短款', '冬季', '春装']};
function getTpl(data){//todo...
};
var result = getTplStr(prod); //result为下面的字符串
<dl class="product">
<dt>女装</dt> 
<dd>短款</dd>
<dd>冬季</dd>
 <dd>春装</dd>
</dl>
使用数组拼接出如下字符串

代码预览


var arr = [ "test", 2, 1.5, false ]
find(arr, "test") // 0
find(arr, 2) // 1
find(arr, 0) // -1
find函数

代码预览


arr = ["a", "b", 1, 3, 5, "b", 2];
newarr = filterNumeric(arr); // [1,3,5,2]
函数filterNumeric

代码预览


var obj = { 
className: 'open menu'
}
addClass(obj, 'new') // obj.className='open menu new'
addClass(obj, 'open') // 因为open已经存在,所以不会再次添加open
addClass(obj, 'me') // me不存在,所以 obj.className变为'open menu new me'
console.log(obj.className) // "open menu new me"
removeClass(obj, 'open') // 去掉obj.className里面的 open,变成'menu new me
'removeClass(obj, 'blabla') // 因为blabla不存在,所以此操作无任何影响
addClass、removeClass函数

代码预览


camelize("background-color") == 'backgroundColor'
camelize("list-style-image") == 'listStyleImage'
转换

代码预览


arr = ["a", "b"];
arr.push( function() { 
alert(console.log('hello hunger valley'))
    } );//push把函数 alert(console.log('hello hunger valley')) 放入arr数组末尾
arr[arr.length-1]() // 输出数组最后一个console.log('hello hunger valley')
结果
arr = ["a", "b", 1, 3, 4, 5, "b", 2];
//对原数组进行操作,不需要返回值
filterNumericInPlace(arr);
console.log(arr) // [1,3,4,5,2]
Paste_Image.png
var john = { name: "John Smith", age: 23 }
var mary = { name: "Mary Key", age: 18 }
var bob = { name: "Bob-small", age: 6 }
var people = [ john, mary, bob ]
ageSort(people) // [ bob, mary, john ]
ageSort


function isNumeric (el){ return typeof el === 'number'; }
arr = ["a",3,4,true, -1, 2, "b"]
arr = filter(arr, isNumeric) ; // arr = [3,4,-1, 2], 过滤出数字
arr = filter(arr, function(val) { return typeof val === "number" && val > 0 }); // arr = [3,4,2] 过滤出大于0的整数
Image.png

代码预览


字符串

ucFirst("hunger") == "Hunger"
首字母大写

代码预览


truncate("hello, this is hunger valley,", 10)) == "hello, thi...";
truncate("hello world", 20)) == "hello world"
截断

代码预览


数学函数

function rand1(min,max){
 return Math.floor(Math.random()*(max-min))+min;
}
function rand2(min, max) {
 return Math.floor(Math.random() * (max - min + 1))+min;
}
function arrRand(len,min,max){
 var arr = [];
 for(var i=0; i<len; i++){
     arr.push(rand2(min,max));
 }

 return arr;
}
function getRandStr(len){ 
//todo...
}
var str = getRandStr(10); // 0a3iJiRZap
随机字符串

代码预览


              本文版权归作者饥人谷_Josh和饥人谷所有,转载请注明来源
上一篇 下一篇

猜你喜欢

热点阅读