从string中选择随机数组元素,但相同的字符串始终返回相同的元素。伪随机

问题描述 投票:-2回答:3

我在Javascript中有一系列可能的颜色:

possibleColors = [
        "#10ace3",
        "#f26529",
        "#c62328",
        "#e53434",
        "#ffba49",
        "#99c24d",
        "#7e1d1d"
      ]

给定一个字符串(该人的名字),我想随机选择相同的颜色。

举个例子:

"Sergio" would always return the first color.
"Daniel" would always return the fourth color.
etc.

有关如何做到这一点的任何建议?请不要从字面上看我的例子我只是意味着相同的字符串应该返回相同的颜色。

javascript arrays random ecmascript-6
3个回答
0
投票

如果动态给出名称,则必须在第一个条目上为其指定颜色,然后确保每个后续条目返回相同的颜色。

如果您事先知道名称,那么您只需创建一个地图以返回相同的颜色。

无论如何,必须创建一些排序映射。

例如:

const nameColorMap = new Map()
const possibleColors = [ "#10ace3", "#f26529", "#c62328", "#e53434", "#ffba49", "#99c24d", "#7e1d1d"]

function getColorForName(name) {
  if (!nameColorMap.has(name)) {
    const color = possibleColors[Math.round(Math.random() * possibleColors.length)]
    nameColorMap.set(
      name,
      color,
    )
  }

  return nameColorMap.get(name)
}

https://repl.it/@baruchvlz/GrubbyAgonizingOffice


0
投票

只要存放人名和他们的颜色,如果他是一个新人,就给他带一个随机颜色,相反地返回他的颜色。

const possibleColors = [
  "#10ace3",
  "#f26529",
  "#c62328",
  "#e53434",
  "#ffba49",
  "#99c24d",
  "#7e1d1d"
];

let  getColor = (function() {
  let cache = {};
  let f = function(name) {
    if (!cache[name]) {
      cache[name] = possibleColors[Math.floor(Math.random() * possibleColors.length)];
    }

    return cache[name];
  }
  return f;
})();

console.log(getColor('Sergio'));
console.log(getColor('Sergio'));
console.log(getColor('Sergio'));

console.log(getColor('Daniel'));
console.log(getColor('Daniel'));
console.log(getColor('Daniel'));

0
投票

您将需要利用某种存储,例如localStorage或后端数据库,例如MySQL

由于SO不支持localStorage片段,这里是以下代码的jsfiddle

const possibleColors = [
        "#10ace3",
        "#f26529",
        "#c62328",
        "#e53434",
        "#ffba49",
        "#99c24d",
        "#7e1d1d"
      ]

function getColor(str) {
  // Attempt the get the item from local storage (returns null otherwise)
  let color = localStorage.getItem(str)
  if(!color) {
    // Nothing was in local storage, select a random color
    color = possibleColors[Math.floor(Math.random() * possibleColors.length)]
    // Save the color to local storage for use next time
    localStorage.setItem(str, color)
  }
  // Return the color that was or now is in local storage
  return color
}

console.log('jim', getColor('jim'))
console.log('bob', getColor('bob'))

console.log('jim', getColor('jim'))
console.log('brass monkey', getColor('brass monkey'))
console.log('jim', getColor('jim'))

console.log('brass monkey', getColor('brass monkey'))
console.log('brass monkey', getColor('brass monkey'))

多次重新运行脚本将使用相同的字符串给出相同的结果。重新加载页面将执行相同的操作,因为值存储在存储中。

// Example possible output:
//
// jim           #7e1d1d
// bob           #c62328
// jim           #7e1d1d
// brass monkey  #e53434
// jim           #7e1d1d
// brass monkey  #e53434
// brass monkey  #e53434
© www.soinside.com 2019 - 2024. All rights reserved.