数组、字符串&函数-Assignment

2016-06-20  本文已影响61人  犯迷糊的小羊

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

新建一个数组

var array= new Array(1,"hello","world")
array.push("!")//4
array//[1, "hello", "world", "!"]
array.unshift("0")//5
array//["0", 1, "hello", "world", "!"]
array.pop()//"!"
array//["0", 1, "hello", "world"]
array.shift()//"0"
array//[1, "hello", "world"]
array//[1, "hello", "world"]
array.splice(1,2,"你好","生活")//["hello", "world"]
array//[1, "你好", "生活"]
array.join("---")//"1---你好---生活"

2. 数组类

var array = new Array (1,"hello","world");
array.push("!")等价于array.splice(3,0,"!")
array.pop()等价于array.splice(2,1)
array.unshift("good")等价于array.splice(0,0,"good")
array.shift()等价于array.splice(0,1)
//思路:
//1.先建立数组arr,将所有元素输入数组;
//2.在使用for或者for in进行遍历
var prod = {
    name: '女装',
    styles: ['短款', '冬季', '春装']
};
function getTplStr(data){
    var i,arr = [];
    for(i=0;i<data.styles.length;i++){
    arr.push("<dt>" + data.styles[i] + "</dt>\n")
    }
//for (key in data.styles){"<dt>" + data.styles[key] + "</dt>\n"}
//另一种遍历数组方法
    arr.unshift('<dl class="product">\n');
    arr.splice(1,0,"<dt>"+data.name+"</dt>\n")
    arr.push("</dl>")
    return arr.join("");
}
var result = getTplStr(prod);
console.log(result)
//思路1:
//利用数组的继承自原型对象的indexOf()方法,可以返回某个值表示是否属于数组
var arr = [ "test", 2, 1.5, false ]
function find(array,value){
    var testValue;
    testValue = array.indexOf(value)
    console.log(testValue)
}
find(arr,"test")        
find(arr, false)
find(arr, 0) 

//思路2:
//利用for in 去遍历数组元素是否与输入值相一致的思维
var arr = [ "test", 2, 1.5, false ]
function find(array,value) {
    var index=-1,key;
  if (!!array && array.length > 0)
    for ( key in array){
      if (value === array[key]){
          index = key;
      } 
     }
  else{
    console.log("Not a Array or Array.length <=0")
  }
     console.log(index)
}                 
//思路
//1.传入一个数组入函数
//2.遍历数组,如果数组元素是数值型则push进入定义的新数组nArr
//3.输出数组
【注】数组的方法在处理删除“当前的某个元素”操作在下面一道题有另一种思路,这里主要方法是通过新建一个空数组+push()的方法实现该需求
arr = ["a", 1,3,5, "b", 2];
newarr = filterNumeric(arr);
console.log(newarr)
function filterNumeric(array){
  var i,nArr=[];
  for (i=0;i<array.length;i++){
    if(typeof array[i] === "number" ){
      nArr.push(array[i])
    }
  }
  return nArr
}
//思路
//1.输入的clasName要和数组元素进行匹配
//如果className和第1个元素同名,则停止运行函数,并返回XXX已存在
//否则className和第2个元素进行匹配,若同名停止运行函数,并返回XXX已存在
//一直匹配下去,直到匹配到最后1个元素,
//如果与所有数组元素均不同名,则使用XXX.push(classContent)
var obj = {
  className: 'open menu new'
}
function addClass(obj,classContent){
  
  var objArr,key,i;
  objArr = obj.className.split(" ")
  for (i=0;i<objArr.length;i++){
    if (classContent === objArr[i]){
      console.log(classContent+"已存在")
      break;
    }
  }
  if (i === objArr.length){
      objArr.push(classContent)
    }    
  obj.className = objArr.join(" ")
     console.log(obj.className)
}
addClass(obj,"open")

-----------------------------------------------------------
function removeClass(obj,classContent){
  var objArr,key,i;
  objArr = obj.className.split(" ")
  for (i=0;i<objArr.length;i++){
    if (classContent === objArr[i]){
      objArr.splice(i,1)
      break;
     }
  }
  if (i === objArr.length){
    console.log(classContent+"不存在")
  }
   obj.className = objArr.join(" ")
   console.log(obj.className)
}
removeClass(obj,"new")
camelize("my-short-string")
camelize("background-color")
camelize("list-style-image")
function camelize(str){
  var i,strArr,midArr,upCaseFL,finalArr
  strArr = str.split("-") //strArr = ["my","short","string"]
  if (strArr.length > 1){
    for (i=1;i<strArr.length;i++){
      midArr = strArr[i].split("")//midArr = ["s","h","o","r","t"]
       upCaseFL = midArr[0].toUpperCase();//unCaseFL = "S"
       midArr.splice(0,1,upCaseFL)
       finalArr = midArr.join("")//finalArr = "Short"
       strArr[i] = finalArr//str[1] = "Short"
    }
  }
  return strArr.join("")//"myShortString"
}
arr[arr.length-1]() 
输出结果:
控制台输出:hello hunger valley
弹出窗口显示:undefined
上述代码的执行过程为:
1.向数组arr的最后一个下标添加一个函数
2.arr[arr.length-1]()为读取arr的最后元素——函数并执行
arr = ["a", 1,3,4,5, "b", 2];
//对原数组进行操作,不需要返回值
function filterNumericInPlace(array){
  var key;
  for (key in array){
    if (typeof array[key] !== "number"){
      array.splice(key,1)
    }
  }       
}
filterNumericInPlace(arr);
console.log(arr)  // [1,3,4,5,2]
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(people){
  function sortNumber(o1,o2){
    return o1.age-o2.age
  }
}
arr = ["a",3,4,true, -1, 2, "b"]
function isNumeric (el){
  return typeof el === "number";
}
function filter(arr,func){
  var i;
  for (i=0;i<arr.length;i++){
  if (!func(arr[i])){
    arr.splice(i,1)
    i--;
  }  
  }
  return arr
}
arr = filter(arr, isNumeric) ; 
console.log(arr);//  [3,4,-1, 2],  过滤出数字
arr = filter(arr, function(val) { return val > 0 });  
console.log(arr);// [3,4,2] 过滤出大于0的整数

3.字符串

ucFirst("hunger");
function ucFirst(str){
   var strArr,upCaseFL
   strArr = str.split("")//strArr=["h","u","n","g","e","r"]
   upCaseFL = strArr[0].toUpperCase();
   strArr.splice(0,1,upCaseFL)
   return strArr.join("");
}
//思路
//1.1如果字符串长度大于给定的最大长度n
//2.截取从第1个字符至maxlength的字符,并添加"..."
//1.2如果小于或等于n,则输出原来值
function truncate(str,maxlength){
  var newStr
  if (str.length > maxlength){
    newStr = str.substring(0,maxlength)+"..."
    console.log(newStr)
  }else {
    console.log(str)
  }
}
truncate("hello, this is hunger valley,", 10) 
truncate("hello world", 20)

4.数学函数

var num1 = 3.456
function limit2(num){
    return round(num*100)/100
}
limit2( num1);
limit2(2.42)
function getRandomArbitrary(min,max){
  var value;
  value = Math.random()*(max-min)+min
  return value;
}
getRandomArbitrary(1.5,3)
function getRandomInt(min,max){
  var value;
  value = Math.floor(Math.random()*(max-min+1))+min
  return value;
}
getRandomInt(1,7);
function randomArr(arrLength,min,max){
  var i,value,arr=[];
  for (i=0;i<arrLength;i++){
    value = Math.floor(Math.random()*(max-min+1))+min
    arr.push(value);
  }
  return arr
}
randomArr(10,10,100)
上一篇下一篇

猜你喜欢

热点阅读