日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Array.prototype.myjoin

作者:web半晨 更新時間: 2022-06-06 編程語言


1、概念

join()方法將一個數組(或一個類數組對象)的所有元素連接成一個字符串并返回這個字符串。如果數組只有一個項目,那么將返回該項目而不使用分隔符。


2、MDN鏈接地址

MDN - join


3、示例代碼

let arrayData = [1, null, [2], 'string', [], { sname: 3 }, null, {}];

Array.prototype.myjoin = function(separator) {
	// 如果 separator 是字符串類型,
	// 賦值為 separator ;
	// 否則,賦值為 , 。
	separator = typeof separator === 'string' ? separator : ',';

	// 獲取 this 的長度。
	let len = this.length;

	// 初始化一個字符串
	let str = '';

	// 如果 len 等于 0 ,
	// 返回空字符串
	if (!len) return str;

	// 初始化 while 循環條件
	let i = 1;

	// 如果 this 的長度等于 1 ,
	// 直接返回且不加 , 。
	str = this[0] ? this[0].toString() : '';

	while (i < len) {
		str += separator + (this[i] ? this[i].toString() : '');

		i++;
	};

	return str;
};

console.log(arrayData.myjoin());
// 1,,2,string,,[object Object],,[object Object]

console.log(arrayData.myjoin(','));
// 1,,2,string,,[object Object],,[object Object]

console.log(arrayData.myjoin('_'));
// 1__2_string__[object Object]__[object Object]

console.log(arrayData.myjoin(':'));
// 1::2:string::[object Object]::[object Object]

原文鏈接:https://blog.csdn.net/weixin_51157081/article/details/115795531

欄目分類
最近更新