JavaScript数组、字符串、数学函数的知识点

问答

  • 数组方法里push、pop、shift、unshift、join、split分别是什么作用。
    push()方法添加一个或多个元素到数组的末尾,并返回数组新的长度(length 属性值)。
    pop() 方法删除一个数组中的最后的一个元素,并且返回这个元素。
    shift()方法删除数组的第一个元素,并返回这个元素。该方法会改变数组的长度。
    unshift() 方法在数组的开头添加一个或者多个元素,并返回数组新的 length 值。
    join()方法将数组中的所有元素连接成一个字符串。
    **split() **方法通过把字符串分割成子字符串来把一个 String对象分割成一个字符串数组。

代码题

数组

  • 用 splice 实现 push、pop、shift、unshift方法
    定义和用法
    splice() 方法用于插入、删除或替换数组的元素。
    语法
    arrayObject.splice(index,howmany,element1,…..,elementX)
    参数描述
    index 必需。规定从何处添加/删除元素。该参数是开始插入和(或)删除的数组元素的下标,必须是数字。
    howmany 必需。规定应该删除多少元素。必须是数字,但可以是 “0”。如果未规定此参数,则删除从 index 开始到原数组结尾的所有元素。element1 可选。规定要添加到数组的新元素。从 index 所指的下标处开始插入。
    elementX 可选。可向数组添加若干元素。
    返回值
    如果从 arrayObject 中删除了元素,则返回的是含有被删除的元素的数组。
    splice->push
    var a = [1,2,3,4,5]
    var b = [1,2,3,4,5]
    console.log(a);
    console.log(b);
    a.push(6);
    b.splice(5,1,6);
    console.log(a);
    console.log(b);
    splice->pop
    var a = [1,2,3,4,5]
    var b = [1,2,3,4,5]
    console.log(a);
    console.log(b);
    a.pop();
    b.splice(4,1);
    console.log(a);
    console.log(b);
    splice->shift
    var a = [1,2,3,4,5]
    var b = [1,2,3,4,5]
    console.log(a);
    console.log(b);
    a.shift();
    b.splice(0,1);
    console.log(a);
    console.log(b);
    splice->unshift
    var a = [1,2,3,4,5]
    var b = [1,2,3,4,5]
    console.log(a);
    console.log(b);
    a.unshift(-1);
    b.splice(0,0,-1);
    console.log(a);
    console.log(b);
  • 使用数组拼接出如下字符串
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 prod = {
name: ‘女装’,
styles: [‘短款’, ‘冬季’, ‘春装’]
};
function getTplStr(data){
var htmls = [];
htmls.push(‘<dl class=”product”>’,'<dt>’+data,name+'<dt>’);
for(i=0;i<data.styles.length;i++){
htmls.push(‘<dd>’+data.styles[i]+'<dd>’)
}
htmls.push(‘<dl>’);
var htmls = htmls.join(”)
return htmls
};
var result = getTplStr(prod); //result为下面的字符串
console.log(result)

  • 写一个find函数,实现下面的功能
    var arr = [ “test”, 2, 1.5, false ]
    find(arr, “test”) // 0
    find(arr, 2) // 1
    find(arr, 0) // -1
    代码:
    var arr = [ “test”, 2, 1.5, false ]
    var find = function(a,b){
    console.log(a.indexOf(b))
    }
    find(arr, “test”) // 0
    find(arr, 2) // 1
    find(arr, 0) // -1

  • 写一个函数filterNumeric,实现如下功能
    arr = [“a”, 1,3,5, “b”, 2];
    newarr = filterNumeric(arr); // [1,3,5,2]
    代码:
    方法一:
    arr = [“a”, 1,3,5, “b”, 2];
    var filterNumberic = function(data){
    var a = [];
    for(i=0;i<data.length;i++){
    if(typeof data[i] === ‘number’){
    a.push(data[i]);
    }
    }
    return a
    }
    newarr = filterNumberic(arr); // [1,3,5,2]
    console.log(newarr)
    方法二:
    arr = [“a”, 1,3,5, “b”, 2];
    function isNumber(element) {
    return typeof element === ‘number’;
    }
    var newarr = arr.filter(isNumber)
    console.log(newarr)

  • 对象obj有个className属性,里面的值为的是空格分割的字符串(和html元素的class特性类似),写addClass、removeClass函数,有如下功能:
    var obj = {
    className: ‘open menu’
    }
    addClass(obj, ‘new’) // obj.className=’open menu new’
    addClass(obj, ‘open’) // 因为open已经存在,此操作无任何办法
    addClass(obj, ‘me’) // obj.className=’open menu new me’
    console.log(obj.className) // “open menu new me”

      removeClass(obj, 'open') // obj.className='menu new me'
      removeClass(obj, 'blabla')  // 不变
    

代码:
var obj = {
className: ‘open menu’
}
var addClass = function(a,b){
var name = a.className.split(” “);
if(name.indexOf(b) === -1) {
name.push(b);
}
else{
console.log(“因为”+b+”已经存在,此操作无任何办法”);
}
a.className = name.join(” “);
console.log(‘obj.className=’+a.className);
}
var removeClass = function(a,b){
var name = a.className.split(” “);
if(name.indexOf(b) !== -1){
name.splice(name.indexOf(b),1)
a.className = name.join(” “);
console.log(‘obj.className=’+a.className)
}else{console.log(‘不变’)}
}

    addClass(obj, 'new') // obj.className='open menu new'
    addClass(obj, 'open')  // 因为open已经存在,此操作无任何办法
    addClass(obj, 'me') // obj.className='open menu new me'
    console.log(obj.className)  // "open menu new me"

    removeClass(obj, 'open') // obj.className='menu new me'
    removeClass(obj, 'blabla')  // 不变
  • 写一个camelize函数,把my-short-string形式的字符串转化成myShortString形式的字符串,如:
    camelize(“background-color”) == ‘backgroundColor’
    camelize(“list-style-image”) == ‘listStyleImage’
    代码:
    function camelize(string){
    return string.replace(/-/g,”)
    }
    console.log(camelize(“background-color”))
    camelize(“background-color”) == ‘backgroundColor’
    camelize(“list-style-image”) == ‘listStyleImage’

  • 如下代码输出什么?为什么?
    arr = [“a”, “b”];
    arr.push( function() { alert(console.log(‘hello hunger valley’)) } );
    arrarr.length-1 // ?
    因为arr.push( function() { alert(console.log('hello hunger valley')) } );function() { alert(console.log('hello hunger valley')push到arr[]最后一位,arr[arr.length-1]()取该数组最后一位,然后立即执行该函数,由于function() { alert(console.log('hello hunger valley')console.log只允许在控制台中打开,所以结果为undefined

  • 写一个函数filterNumericInPlace,过滤数组中的数字,删除非数字
    arr = [“a”, 1,3,4,5, “b”, 2];
    //对原数组进行操作,不需要返回值
    filterNumericInPlace(arr);
    console.log(arr) // [1,3,4,5,2]
    代码:
    arr = [“a”,”d”, 1,3,4,5, “b”, 2];
    //对原数组进行操作,不需要返回值
    function filterNumericInPlace(data){
    for(i=0;i<data.length;i++){
    if(typeof data[i] === ‘string’){
    data.splice(i,1);
    i–;//splice指针减少1,否则获取不了数组中全部元素。
    }
    }
    }
    filterNumericInPlace(arr);
    console.log(arr) // [1,3,4,5,2]

  • 写一个ageSort函数实现如下功能:
    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 ]
    代码:
    方法一:
    function ageSort(arr){
    arr.sort(function(a,b){return a.age-b.age})
    return arr
    }
    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 ]
    console.log(ageSort(people))
    方法二:
    function ageSort(a){
    for(i=0;i<a.length;i++){
    for(j=i+1;j<a.length;j++){
    if(a[i].age-a[j].age>0){
    var b = a[i];
    a[i] = a[j];
    a[j] = b;
    }
    }
    }
    return a
    }
    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 ]
    console.log(ageSort(people))

  • 写一个filter(arr, func) 函数用于过滤数组,接受两个参数,第一个是要处理的数组,第二个参数是回调函数(回调函数遍历接受每一个数组元素,当函数返回true时保留该元素,否则删除该元素)。实现如下功能:
    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 val > 0 });  // arr = [2] 过滤出大于0的整数
    

代码:
function filter(data,callback){
return data.filter(callback)
}

    function isNumeric (el){
        return typeof el === 'number'; 
    }
    arr = ["a",3,4,true, -1, 2, "b"]

    arr = filter(arr, isNumeric) ; // arr = [3,4,-1, 2],  过滤出数字
    console.log(arr)
    arr = filter(arr, function(val) { return val > 0 });  // arr = [2] 过滤出大于0的整数
    console.log(arr)

字符串

  • 写一个 ucFirst函数,返回第一个字母为大写的字符。
    ucFirst(“hunger”) == “Hunger”
    代码:
    function ucFirst(string){
    return string[0].toUpperCase()+string.slice(1);
    }
    console.log(ucFirst(“hunger”))
    ucFirst(“hunger”) == “Hunger”
  • 写一个函数truncate(str, maxlength), 如果str的长度大于maxlength,会把str截断到maxlength长,并加上…,如:
    truncate(“hello, this is hunger valley,”, 10)) == “hello, thi…”;
    truncate(“hello world”, 20)) == “hello world”
    代码:
    function truncate(str,maxlength){
    if(str.length>maxlength){
    var sub = str.substring(maxlength)
    str = str.replace(sub,’…’);
    } return str;
    }
    console.log(truncate(“hello, this is hunger valley,”, 10));
    truncate(“hello, this is hunger valley,”, 10) == “hello, thi…”;
    truncate(“hello world”, 20) == “hello world”

数学函数

  • 写一个函数limit2,保留数字小数点后两位,四舍五入,如:
    var num1 = 3.456
    limit2( num1 ); //3.46
    limit2( 2.42 ); //2.42
    代码:
    var num1 = 3.456
    function limit2(data){
    var num = Math.round(data*100);
    return num/100
    }
    limit2( num1 ); //3.46
    limit2( 2.42 ); //2.42
    console.log(limit2(num1));
    console.log(limit2(2.42));
    console.log(limit2(-1.15555555))
  • 写一个函数,获取从min到max之间的随机数,包括min不包括max。
    代码:
    function fun(min,max){
    return min+Math.random()*(max-min)
    }
    console.log(fun(5,10))
  • 写一个函数,获取从min都max之间的随机整数,包括min包括max。
    代码:
    function fun(min,max){
    return Math.Round(min+Math.random()*(max-min))
    }
    console.log(fun(5,10))
  • 写一个函数,获取一个随机数组,数组中元素为长度为len,最小值为min,最大值为max(包括)的随机数 .
    代码:
    function fun(min,max,leng){
    var arr = []
    for(i=0;i<leng;i++){
    var value = max-Math.random()*(max-min)
    arr.push(value)
    }
    return arr
    }
    console.log(fun(5,10,6))
    原文作者:张新望zxw
    原文地址: https://www.jianshu.com/p/9c15fdac96a0
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞