美文网首页
数组练习

数组练习

作者: __马帅傅__ | 来源:发表于2017-09-16 15:55 被阅读0次

1.查找数组包含的字符串:

function arrayFindString(arr , string){

var str = arr.join("");

return str.indexOf(string);   }

2.定义一个方法,传入一个string类型的参数,将string的每一个字符见加个空格返回。

function spacify(str){ return str.split('').join(' '); }

spacify('hello world');  // h e l l o   w o r l d

如何将这个方法放入String对象上面

String.prototype.spacify = function() { return this.split('').join(' '); };

'hello world'.spacify();  // h e l l o  w o r l d

3.定义一个log方法,它可以代理console.log的方法。

function log(msg){ console.log(msg); }

改变调用log的方式,传入多个参数,个数不定。

如: log('hello','world');

用apply,代码如下:

function log(){ console.log.apply(console,arguments) };

给每一个log消息添加一个"(app)"的前缀:

‘(app) hello world’

arguments是一个假数组,将它转化成为标准数组,通常方法是使用Array.prototype.slice。

function log(){

var args = Array.prototype.slice.call(arguments);

args.unshift('(app)');

console.log.apply(console,args); }

关于 Array.prototype.slice.call(arguments,1):

function test(a,b,c,d) {var arg =Array.prototype.slice.call(arguments,1);

//  function test(a,b,c,d) {var arg =Array.prototype.slice.call([a,b,c,d],1);

alert(arg); }

test("a","b","c","d");//b,c,d

换个参数:

function test(a,b,c,d) {var arg =Array.prototype.slice.call(arguments,0);

test("a","b","c","d");//a,b,c,d

相关文章

网友评论

      本文标题:数组练习

      本文链接:https://www.haomeiwen.com/subject/xhzysxtx.html