JavaScript數組-字符串-數學函數
發表時間:2023-09-16 來源:明輝站整理相關軟件相關文章人氣:
[摘要]這次給大家帶來JavaScript數組-字符串-數學函數,使用JavaScript數組-字符串-數學函數的注意事項有哪些,下面就是實戰案例,一起來看一下。數組方法里push、pop、shift、unshift、join、split分別是什么作用。push()方法添加一個或多個元素到數組的末尾,并返...
這次給大家帶來
JavaScript數組-字符串-數學函數,
使用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))
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
相關閱讀:
JS的閉包與定時器
JS的Dom與事件小結
以上就是JavaScript數組-字符串-數學函數的詳細內容,更多請關注php中文網其它相關文章!
網站建設是一個廣義的術語,涵蓋了許多不同的技能和學科中所使用的生產和維護的網站。