js shuffle array︱js隨機打亂數組

javascript打亂數組。

方法一:

		Object.defineProperty(Array.prototype, 'shuffle', {
			value: function() {
				for (let i = this.length - 1; i > 0; i--) {
					const j = Math.floor(Math.random() * (i + 1));
					[this[i], this[j]] = [this[j], this[i]];
				}
				return this;
			}
		});

方法二:

		if (!Array.prototype.shuffle) {
			Array.prototype.shuffle = function() {
				for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
				return this;
			};
		}

Leave a Comment